package com.igeek.boot.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author fengqq
 * @Description 基于数据库进行认证用户信息的配置
 * @Date 2024/9/13  16:01
 */
@Configuration
@EnableWebSecurity
public class SecurityInDBConfig extends WebSecurityConfigurerAdapter {

    //认证失败处理器
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    //授权失败处理器
    private AccessDeniedHandler accessDeniedHandler;
    @Autowired
    //解析token过滤器
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    //加密方式
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 认证配置
     * anonymous()：匿名访问：未登录可以访问，已登录不能访问
     * permitAll()：有没有认证都能访问：登录或未登录都能访问
     * denyAll(): 拒绝
     * authenticated()：认证之后才能访问
     * hasAuthority()：包含权限
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            //关闭CSRF（跨服务器的请求访问）,默认是开启的，设置为禁用；如果使用自定义登录页面需要关闭此项，否则登录操作会被禁用403
            .csrf().disable()
            // 禁用session (前后端分离项目，不通过Session获取SecurityContext)
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            //请求认证配置
            .authorizeRequests()
            .antMatchers("/admin/login").permitAll()  //登录或未登录都可以访问，直接放行的资源
            .anyRequest().authenticated();      //任意用户，认证通过才可以访问

        // 添加token过滤器    自动检验密码UsernamePasswordAuthenticationFilter
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // 配置异常处理器
        http.exceptionHandling()
                //认证失败
                .authenticationEntryPoint(authenticationEntryPoint)
                //授权失败
                .accessDeniedHandler(accessDeniedHandler);

        // Spring Security 允许跨域
        http.cors();
    }

    //基于数据库进行用户认证  --》 启动UserDetailsService
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
